package com.cloud.base.designmode.strategy;

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Component
public class StrategyFactory {
    private static final Map<String, ServiceInterface> SERVICE_MAP = Maps.newHashMap();

    @Autowired
    public void setServiceMap(ServiceInterface[] serviceArray) {
        for (ServiceInterface service : serviceArray) {
            SqlTableAnnotation annotation = service.getClass().getAnnotation(SqlTableAnnotation.class);
            String value = annotation.tableName();
            String lastPackage = lastPackage(service.getClass());
            SERVICE_MAP.put(lastPackage + "$" + value, service);
        }
        System.out.println(SERVICE_MAP);
    }

    private String lastPackage(Class<?> clazz) {
        Package aPackage = clazz.getPackage();
        List<String> packageList = Arrays.asList(aPackage.getName().split("\\."));
        Collections.reverse(packageList);
        return packageList.get(0);
    }

    // 传递字符串  返回对象
    public static ServiceInterface getService(String key) {
        ServiceInterface service = SERVICE_MAP.get(key);
        return service;
    }
}
